package com.hhh.demo.sx.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hhh.demo.sx.bean.User;
import com.hhh.demo.sx.exception.MyException;
import com.hhh.demo.sx.service.UserService;
import com.hhh.demo.sx.util.MD5Util;
import com.hhh.demo.sx.util.ResultMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hhh
 * @since 2021-12-27
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;


    /**
     * 打开用户主页面
     */
    @RequestMapping("/index")
    public String openPage() {
        return "user";
    }

    /**
     * 查询用户列表
     */
    @ResponseBody
    @RequestMapping("/list")
    public Map<String, Object> getList(@RequestParam("page") int p,
                                       @RequestParam("limit") int limit,
                                       @RequestParam(value = "condition", required = false) String condition) {

        return userService.findAll(p, limit, condition);

    }

    /**
     * 新增/修改用户
     */
    @ResponseBody
    @RequestMapping("/saveOrUpdate")
    public ResultMap saveOrUpdate(User user) {

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        if (userService.getOne(wrapper) != null&&user.getId()==null) {
            throw new MyException("用户名已存在");

        }
        user.setPassword(MD5Util.md5(user.getPassword()));
        boolean f = userService.saveOrUpdate(user);
        if (f) {
            return ResultMap.success();
        } else {
            return ResultMap.fail();
        }
    }

    /**
     * 查找用户
     */
    @ResponseBody
    @RequestMapping("/getOne")
    public ResultMap getOne(int id) {
        User user = userService.getById(id);
        return ResultMap.success(user);
    }

    /**
     * 删除用户
     */
    @ResponseBody
    @RequestMapping("/delete")
    public ResultMap delete(int id) {
        boolean f = userService.removeById(id);
        if (f) {
            return ResultMap.success();
        } else {
            return ResultMap.fail();
        }
    }
}

